package com.future.lock.home.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.future.baselib.activity.BaseActivity;
import com.future.baselib.entity.MessageEvent;
import com.future.baselib.utils.EventBusUtil;
import com.future.baselib.view.CustomViewCenterDialog;
import com.future.lock.R;
import com.future.lock.common.Constants;
import com.future.lock.common.MyApp;
import com.future.lock.common.RefreshDataUtils;
import com.future.lock.common.activity.MainActivity;
import com.future.lock.common.http.HttpUtils;
import com.future.lock.common.http.response.DefaultHttpResponse;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AddLockStep2Activity extends BaseActivity {

    @BindView(R.id.view_line)
    View viewLine;
    @BindView(R.id.textView)
    TextView textView;
    private String mac;

    private int connTimeOut = 59;
    private boolean isConnecting = true;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1 && isConnecting) {
                if (connTimeOut <= 0){
                    textView.setText("智能锁添加失败");
                    showFailDialog();
                    return;
                }
                if (connTimeOut % 3 == 0) {
                    hasConnected();
                }
                textView.setText("正在匹配智能锁，请稍等...(" + connTimeOut-- + "s)");
                handler.sendEmptyMessageDelayed(1, 1000);
            }
        }
    };


    @Override
    protected void initContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_add_lock_step2);
        ButterKnife.bind(this);
    }

    @Override
    protected void initView() {
        setTitle("");
        viewLine.setVisibility(View.GONE);
        setTitleLeft(R.mipmap.ic_exit, v -> finish());
        hasConnected();
        handler.sendEmptyMessage(1);
    }

    @Override
    protected void initLogic() {
    }

    private void hasConnected() {
        HttpUtils.getHttpApi()
                .addLock(MyApp.getUserToken(), mac)
                .enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {
                        DefaultHttpResponse httpResponse = new DefaultHttpResponse();
                        httpResponse.parse(response.body());
                        if (httpResponse.success == 1) {
                            isConnecting = false;
                            textView.setText("添加智能锁成功！");
                            showSuccessDialog();
                        }else{
                            if (httpResponse.code == 112) {
                                RefreshDataUtils.logout(AddLockStep2Activity.this);
                            }
                            if (!"未检测到可绑定的锁!".equals(httpResponse.msg)) {
                                isConnecting = false;
                                showFailDialog();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {
                        isConnecting = false;
                        showFailDialog();
                    }
                });
    }

    private void showSuccessDialog() {
        View rootView = getLayoutInflater().inflate(R.layout.dialog_default, null);
        ((TextView) rootView.findViewById(R.id.tv_message)).setText("智能锁添加成功");
        Button btnCancel = (Button) rootView.findViewById(R.id.btn_cancel);
        btnCancel.setVisibility(View.GONE);
        rootView.findViewById(R.id.view_line).setVisibility(View.GONE);
        Button btnOk = (Button) rootView.findViewById(R.id.btn_ok);
        btnOk.setText("知道了");
        btnOk.setOnClickListener(view -> {
            EventBusUtil.sendEvent(new MessageEvent(Constants.REFRESH_LOCK_DATA));
            startActivity(MainActivity.class);
        });
        new CustomViewCenterDialog(this)
                .setView(rootView)
                .builder()
                .setCancelable(false)
                .show();
    }

    private void showFailDialog() {
        View rootView = getLayoutInflater().inflate(R.layout.dialog_default, null);
        ((TextView) rootView.findViewById(R.id.tv_message)).setText("智能锁添加失败");
        Button btnCancel = (Button) rootView.findViewById(R.id.btn_cancel);
        btnCancel.setVisibility(View.GONE);
        rootView.findViewById(R.id.view_line).setVisibility(View.GONE);
        Button btnOk = (Button) rootView.findViewById(R.id.btn_ok);
        btnOk.setText("重新添加");
        btnOk.setOnClickListener(view -> {
            finish();
        });
        new CustomViewCenterDialog(this)
                .setView(rootView)
                .builder()
                .setCancelable(false)
                .show();
    }

    @Override
    protected void onStop() {
        super.onStop();
        isConnecting = false;
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        mac = extras.getString("mac");
    }
}
